package com.cloud.consumer.feign.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.*;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import org.springframework.cloud.openfeign.clientconfig.OkHttpFeignConfiguration;
import org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName: MyRule
 * @Author: wl
 * @Date: 2021/11/23 11:01
 * @Description: TODO
 */
public class MyRule implements IRule{
    private ILoadBalancer lb;

    @Override
    public Server choose(Object key) {
        // 获取所有servers
        List<Server> allServers = lb.getAllServers();
        List<Server> filterServers = allServers.stream().filter(s -> s.getPort() == 38888).collect(Collectors.toList());
        return filterServers.get(ThreadLocalRandom.current().nextInt(filterServers.size()));
    }

    @Override
    public void setLoadBalancer(ILoadBalancer lb) {
        this.lb = lb;
    }

    @Override
    public ILoadBalancer getLoadBalancer() {
        return lb;
    }

}
